
const gulp = require('gulp')
const browserSync = require('browser-sync').create()
const sass = require('gulp-sass')(require('sass'))
const cleanCSS = require('gulp-clean-css')
const babel = require('gulp-babel')
const uglify = require('gulp-uglify')
const rename = require('gulp-rename')
const sourcemaps = require('gulp-sourcemaps')

//启动服务
function browser (cb) {
    console.log('启动业务')
    browserSync.init({
        watch: true,
        server: './',
        browserSync: [
            "./**/*.css",
            "./**/*.html",
            "./**/*.js",
            "./**/*.png",
            "./**/*.svg",
            "./**/*.jpeg",
            "./**/*.jpg"
        ]
    })
    cb()
}

//scss 转 css
function scssToCss(){
    return gulp.src('./src/scss/*.scss') // 指定你的 .scss 文件路径
        .pipe(sass().on('error', sass.logError)) // 编译 SCSS 文件
        .pipe(gulp.dest('./assets/css')); // 输出到 CSS 目标文件夹
}
//压缩css
function zipCss() {
    return gulp.src('./assets/css/*.css')
        .pipe(cleanCSS({compatibility: 'ie8'}))
        .pipe(rename({ suffix: '.min' })) // 添加.min后缀
        .pipe(gulp.dest('./assets/css'))
}


// Babel配置，将ES6转换为ES5
const babelConfig = {
    presets: ['@babel/preset-env']
}

//压缩js
function scripts(cb) {
    return gulp.src('src/js/**/*.js') // 源文件位置
        .pipe(sourcemaps.init()) // 初始化源映射
        .pipe(babel(babelConfig)) // 使用Babel转换ES6到ES5
        .pipe(uglify()) // 压缩代码
        // .pipe(rename({ suffix: '.min' })) // 添加.min后缀
        .pipe(sourcemaps.write('.')) // 写入源映射到同一目录
        .pipe(gulp.dest('./assets/js')); // 输出位置
}

exports.default = gulp.series(
    scssToCss,
    zipCss,
    scripts,
    browser,
);

gulp.watch('./src/scss/*.scss', gulp.series(scssToCss, zipCss))
gulp.watch('./src/js/*.js', gulp.series(scripts))



